//
//  LBTagsView.m
//  app
//
//  Created by 刘文扬 on 16/11/30.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBTagsView.h"
#import "LBTagCollectionCell.h"
#import "UICollectionViewLeftAlignedLayout.h"
#import "Masonry.h"

static CGFloat const LBTagsViewDefaultTextFontSize = 12;

static CGFloat const LBTagsViewDefaultLeftAndRightMargin = 5;

static CGFloat const LBTagsViewDefaultItemMargin = 10;

static CGFloat const LBTagsViewDefaultRowMargin = 10;

@interface LBTagsView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>





@end

@interface LBTagsView()

/** layoutsubviewWidth*/
@property(nonatomic,assign)CGFloat finishLayoutWidth;

@end

@implementation LBTagsView

-(instancetype)init
{
    self = [super init];
    if (self) {
        _textFont = [UIFont systemFontOfSize:LBTagsViewDefaultTextFontSize];
        _textColor = [UIColor blackColor];
        _leftAndRightMargin = LBTagsViewDefaultLeftAndRightMargin;
        _itemMargin = LBTagsViewDefaultItemMargin;
        _rowMargin = LBTagsViewDefaultRowMargin;
        _dataSource = nil;
        _lb_backgroundImage = nil;
        _imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        
        [self initSubviews];
    }
    return self;
}


-(instancetype)initWithLimitedWidth:(CGFloat)limitedWidth textFont:(UIFont *)textFont textColor:(UIColor *)textColor leftAndRightMargin:(CGFloat)leftAndRightMargin itemMargin:(CGFloat)itemMargin rowMargin:(CGFloat)rowMargin data:(NSMutableArray *)data backgroundImage:(UIImage *)backgroundImage imageEdgeInsets:(UIEdgeInsets)imageEdgeInsets
{
    self = [super init];
    if (self) {
        
        _textFont = textFont;
        _textColor = textColor;
        _leftAndRightMargin = leftAndRightMargin;
        _itemMargin = itemMargin;
        _rowMargin = rowMargin;
        _dataSource = data;
        _lb_backgroundImage = backgroundImage;
        _imageEdgeInsets = imageEdgeInsets;
    
        [self initSubviews];
    }
    return self;
}

-(void)layoutSubviews
{
    if (self.finishLayoutWidth == self.bounds.size.width) {
        return;
    }

    NSLog(@"layoutSubviews bounds %@",NSStringFromCGRect(self.bounds));
    [self invalidateIntrinsicContentSize];
    
    
}


-(CGSize)intrinsicContentSize
{
    self.limitedWidth = self.bounds.size.width;
    if (self.dataSource.count == 0) {
        return CGSizeMake(0, 0);
    }else{
        if (self.bounds.size.width == 0) {
            //证明还没有布局,此时也拿到的bounds也是无效的,所以需要返回一个size触发layoutSubviews
            //来获得真正的bounds来进行布局
            return CGSizeMake(1, 1);
        }
    }
    
    NSArray *arrayData = self.dataSource;
    CGFloat limitedWidth = self.limitedWidth == 0 ? NSIntegerMax : self.limitedWidth;
    CGFloat currentWidth = limitedWidth;
    CGFloat currentMaxWidth = 0;
    CGFloat singleLineHeight = 0;
    NSInteger row = 1;
    for (NSInteger i = 0; i < arrayData.count; ++i) {
        id model = arrayData[i];
        CGSize contentSize = [LBTagCollectionCell sizeForItem:model indexPath:nil totalListNumber:self.dataSource.count leftAndRightMargin:self.leftAndRightMargin textFont:self.textFont itemHeight:self.itemHeight];
        singleLineHeight = contentSize.height;
        
        currentMaxWidth += contentSize.width;
        
        CGFloat itemWidth = contentSize.width + self.itemMargin;
        
        if (currentWidth - itemWidth < 0 && currentWidth - contentSize.width < 0) {
            row++;
            currentWidth = limitedWidth;
        }
        currentWidth -= itemWidth;
        
    }
    CGFloat width = self.limitedWidth == 0 ? (currentMaxWidth + (arrayData.count - 1) * self.itemMargin) : self.limitedWidth;
    self.finishLayoutWidth = self.limitedWidth;
    return CGSizeMake(width, row * singleLineHeight + (row - 1) * self.rowMargin);
}

-(void)setDataSource:(NSMutableArray *)dataSource
{
    _dataSource = dataSource;
    [self invalidateIntrinsicContentSize];
    [self.tagsCollectionView reloadData];
}

-(void)initSubviews
{
    [self addSubview:self.tagsCollectionView];
    [self.tagsCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
       make.edges.insets(UIEdgeInsetsZero);
    }];
}


-(UICollectionView *)tagsCollectionView
{
    if (_tagsCollectionView == nil) {
        
        UICollectionViewLeftAlignedLayout *flowLayout = [[UICollectionViewLeftAlignedLayout alloc] init];
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.minimumLineSpacing = self.rowMargin;
        flowLayout.minimumInteritemSpacing = self.itemMargin;
        _tagsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _tagsCollectionView.backgroundColor = [UIColor whiteColor];
        _tagsCollectionView.delegate = self;
        _tagsCollectionView.dataSource = self;
        _tagsCollectionView.backgroundColor = [UIColor clearColor];
        [_tagsCollectionView registerClass:[LBTagCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([LBTagCollectionCell class])];
        
        
    }
    return _tagsCollectionView;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    LBTagCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LBTagCollectionCell class]) forIndexPath:indexPath];
    
    cell.textFont = self.textFont;
    cell.textColor = self.textColor;
    cell.lb_backgroundImage = self.lb_backgroundImage;
    cell.leftAndRightMargin = self.leftAndRightMargin;
    cell.imageEdgeInsets = self.imageEdgeInsets;
    cell.itemHeight = self.itemHeight;
    cell.haveGapLine = self.haveGapLine;
    cell.itemBackgroundColor = self.itemBackgroundColor;
    cell.lb_selectedBackgroundImage = self.lb_selectedBackgroundImage;
    cell.selectTextColor = self.selectTextColor;
    id model = self.dataSource[indexPath.row];
    [cell configCellWithData:model atIndexPath:indexPath totalListNumber:self.dataSource.count];
    return cell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    id data = self.dataSource[indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(tagsView:didSelectTagIndex:data:)]) {
        
        [self.delegate tagsView:self didSelectTagIndex:indexPath.row data:data];
    }
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return self.rowMargin;
}


-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return self.itemMargin;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    id model = self.dataSource[indexPath.row];
    CGSize size = [LBTagCollectionCell sizeForItem:model indexPath:indexPath totalListNumber:self.dataSource.count leftAndRightMargin:self.leftAndRightMargin textFont:self.textFont itemHeight:self.itemHeight];
    return size;
}

-(void)setTextFont:(UIFont *)textFont
{
    _textFont = textFont;
    [self invalidateIntrinsicContentSize];
    [self.tagsCollectionView reloadData];
}

-(void)setLeftAndRightMargin:(CGFloat)leftAndRightMargin
{
    _leftAndRightMargin = leftAndRightMargin;
    [self invalidateIntrinsicContentSize];
    [self.tagsCollectionView reloadData];
    
}

-(void)setRowMargin:(CGFloat)rowMargin
{
    _rowMargin = rowMargin;
    [self invalidateIntrinsicContentSize];
    [self.tagsCollectionView reloadData];
}

-(void)setItemMargin:(CGFloat)itemMargin
{
    _itemMargin = itemMargin;
    [self invalidateIntrinsicContentSize];
    [self.tagsCollectionView reloadData];
}

-(void)reloadData
{
    [self.tagsCollectionView reloadData];
}

@end




